using System;
using System.Collections.Generic;
using System.Drawing;
using System.Threading.Tasks;
using System.Windows.Forms;
using twistmachinev2.CommonUse;
using twistmachinev2.OPCUA;
using LogManager = twistmachinev2.CommonUse.LogManager;

namespace twistmachinev2
{
    /// <summary>
    /// OPCUA数据监控窗体示例
    /// 展示如何使用新的OPCUA服务架构来订阅和显示数据
    /// </summary>
    public partial class FrmOpcUaDataMonitor : BaseOpcUaForm
    {
        private System.Data.DataTable subscriptionDataTable;
        private DynamicOpcUaMapper dynamicMapper;

        public FrmOpcUaDataMonitor()
        {
            InitializeComponent();
            InitializeDataGridView();
            InitializeDataBinding();
            ApplyModernStyle();
        }

        /// <summary>
        /// 应用现代化样式
        /// </summary>
        private void ApplyModernStyle()
        {
            // 设置窗体样式
            this.BackColor = Color.FromArgb(240, 240, 240);
            this.Font = new Font("Microsoft YaHei UI", 9F, FontStyle.Regular);

            // 设置GroupBox样式
            foreach (Control control in this.Controls)
            {
                if (control is GroupBox groupBox)
                {
                    groupBox.ForeColor = Color.FromArgb(64, 64, 64);
                    groupBox.Font = new Font("Microsoft YaHei UI", 9F, FontStyle.Bold);
                }
            }

            // 设置按钮样式
            StyleButtons(this);

            // 设置DataGridView样式
            StyleDataGridView();
        }

        /// <summary>
        /// 设置按钮样式
        /// </summary>
        private void StyleButtons(Control parent)
        {
            foreach (Control control in parent.Controls)
            {
                if (control is Button button)
                {
                    button.FlatStyle = FlatStyle.Flat;
                    button.FlatAppearance.BorderSize = 1;
                    button.FlatAppearance.BorderColor = Color.FromArgb(200, 200, 200);
                    button.BackColor = Color.White;
                    button.ForeColor = Color.FromArgb(64, 64, 64);
                    button.Font = new Font("Microsoft YaHei UI", 9F, FontStyle.Regular);

                    // 鼠标悬停效果
                    button.MouseEnter += (s, e) =>
                    {
                        button.BackColor = Color.FromArgb(230, 230, 230);
                    };
                    button.MouseLeave += (s, e) =>
                    {
                        button.BackColor = Color.White;
                    };
                }
                else if (control.HasChildren)
                {
                    StyleButtons(control);
                }
            }
        }

        /// <summary>
        /// 设置DataGridView样式
        /// </summary>
        private void StyleDataGridView()
        {
            if (dgvSubscriptions != null)
            {
                dgvSubscriptions.BackgroundColor = Color.White;
                dgvSubscriptions.BorderStyle = BorderStyle.None;
                dgvSubscriptions.CellBorderStyle = DataGridViewCellBorderStyle.SingleHorizontal;
                dgvSubscriptions.ColumnHeadersBorderStyle = DataGridViewHeaderBorderStyle.None;
                dgvSubscriptions.RowHeadersBorderStyle = DataGridViewHeaderBorderStyle.None;

                dgvSubscriptions.ColumnHeadersDefaultCellStyle.BackColor = Color.FromArgb(50, 50, 50);
                dgvSubscriptions.ColumnHeadersDefaultCellStyle.ForeColor = Color.White;
                dgvSubscriptions.ColumnHeadersDefaultCellStyle.Font = new Font("Microsoft YaHei UI", 9F, FontStyle.Bold);
                dgvSubscriptions.ColumnHeadersDefaultCellStyle.SelectionBackColor = Color.FromArgb(50, 50, 50);

                dgvSubscriptions.DefaultCellStyle.BackColor = Color.White;
                dgvSubscriptions.DefaultCellStyle.ForeColor = Color.FromArgb(64, 64, 64);
                dgvSubscriptions.DefaultCellStyle.SelectionBackColor = Color.FromArgb(200, 220, 240);
                dgvSubscriptions.DefaultCellStyle.SelectionForeColor = Color.FromArgb(64, 64, 64);
                dgvSubscriptions.DefaultCellStyle.Font = new Font("Microsoft YaHei UI", 9F, FontStyle.Regular);

                dgvSubscriptions.AlternatingRowsDefaultCellStyle.BackColor = Color.FromArgb(248, 248, 248);
                dgvSubscriptions.GridColor = Color.FromArgb(230, 230, 230);

                dgvSubscriptions.RowHeadersDefaultCellStyle.BackColor = Color.FromArgb(240, 240, 240);
                dgvSubscriptions.RowHeadersDefaultCellStyle.ForeColor = Color.FromArgb(64, 64, 64);
                dgvSubscriptions.RowHeadersDefaultCellStyle.SelectionBackColor = Color.FromArgb(200, 220, 240);
            }
        }

        /// <summary>
        /// 初始化DataGridView
        /// </summary>
        private void InitializeDataGridView()
        {
            // 创建数据表
            subscriptionDataTable = new System.Data.DataTable();
            subscriptionDataTable.Columns.Add("PropertyName", typeof(string));
            subscriptionDataTable.Columns.Add("NodeId", typeof(string));
            subscriptionDataTable.Columns.Add("CurrentValue", typeof(object));
            subscriptionDataTable.Columns.Add("DataType", typeof(string));
            subscriptionDataTable.Columns.Add("IsWritable", typeof(bool));
            subscriptionDataTable.Columns.Add("LastUpdate", typeof(DateTime));

            // 绑定到DataGridView
            dgvSubscriptions.DataSource = subscriptionDataTable;

            // 设置列属性
            dgvSubscriptions.Columns["PropertyName"].HeaderText = "属性名称";
            dgvSubscriptions.Columns["PropertyName"].Width = 120;
            dgvSubscriptions.Columns["PropertyName"].ReadOnly = true;

            dgvSubscriptions.Columns["NodeId"].HeaderText = "节点ID";
            dgvSubscriptions.Columns["NodeId"].Width = 200;
            dgvSubscriptions.Columns["NodeId"].ReadOnly = true;

            dgvSubscriptions.Columns["CurrentValue"].HeaderText = "当前值";
            dgvSubscriptions.Columns["CurrentValue"].Width = 100;
            dgvSubscriptions.Columns["CurrentValue"].ReadOnly = false;

            dgvSubscriptions.Columns["DataType"].HeaderText = "数据类型";
            dgvSubscriptions.Columns["DataType"].Width = 80;
            dgvSubscriptions.Columns["DataType"].ReadOnly = true;

            dgvSubscriptions.Columns["IsWritable"].HeaderText = "可写";
            dgvSubscriptions.Columns["IsWritable"].Width = 60;
            dgvSubscriptions.Columns["IsWritable"].ReadOnly = true;

            dgvSubscriptions.Columns["LastUpdate"].HeaderText = "最后更新";
            dgvSubscriptions.Columns["LastUpdate"].Width = 150;
            dgvSubscriptions.Columns["LastUpdate"].ReadOnly = true;

            // 设置选择模式
            dgvSubscriptions.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
            dgvSubscriptions.MultiSelect = false;

            // 绑定事件
            dgvSubscriptions.CellEndEdit += DgvSubscriptions_CellEndEdit;
            dgvSubscriptions.KeyDown += DgvSubscriptions_KeyDown;
        }

        /// <summary>
        /// 初始化数据绑定
        /// </summary>
        private void InitializeDataBinding()
        {
            //直接绑定数据模型到控件
            dataBindingTextBox1.SetDataBinding(GetDataModel("TwistMachine"), "wendu0", "F0", 0);
        }

        /// <summary>
        /// 获取DynamicMapper实例
        /// </summary>
        private DynamicOpcUaMapper GetDynamicMapper()
        {
            if (dynamicMapper == null)
            {
                var serviceManager = twistmachinev2.OPCUA.OpcUaServiceManager.Instance;
                // 通过反射获取私有字段_dynamicMapper
                var field = serviceManager.GetType().GetField("_dynamicMapper",
                    System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance);
                dynamicMapper = field?.GetValue(serviceManager) as DynamicOpcUaMapper;
            }
            return dynamicMapper;
        }

        /// <summary>
        /// 加载订阅点数据到DataGridView
        /// </summary>
        private void LoadSubscriptionData()
        {
            try
            {
                subscriptionDataTable.Clear();
                var dataModel = GetDataModel("TwistMachine");
                if (dataModel != null)
                {
                    var mapper = GetDynamicMapper();
                    if (mapper != null)
                    {
                        // 通过反射获取配置管理器
                        var configManagerField = mapper.GetType().GetField("configManager",
                            System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance);
                        var configManager = configManagerField?.GetValue(mapper);

                        if (configManager != null)
                        {
                            // 获取所有节点配置
                            var getAllNodesMethod = configManager.GetType().GetMethod("GetAllNodes");
                            var nodeConfigs = getAllNodesMethod?.Invoke(configManager, null) as System.Collections.IEnumerable;

                            if (nodeConfigs != null)
                            {
                                foreach (var nodeConfig in nodeConfigs)
                                {
                                    var propertyNameProp = nodeConfig.GetType().GetProperty("PropertyName");
                                    var nodeIdProp = nodeConfig.GetType().GetProperty("NodeId");
                                    var dataTypeProp = nodeConfig.GetType().GetProperty("DataType");
                                    var isWritableProp = nodeConfig.GetType().GetProperty("IsWritable");

                                    var propertyName = propertyNameProp?.GetValue(nodeConfig)?.ToString();
                                    var nodeId = nodeIdProp?.GetValue(nodeConfig)?.ToString();
                                    var dataType = dataTypeProp?.GetValue(nodeConfig)?.ToString();
                                    var isWritable = isWritableProp?.GetValue(nodeConfig);

                                    var currentValue = dataModel.GetValue(propertyName);

                                    subscriptionDataTable.Rows.Add(
                                        propertyName,
                                        nodeId,
                                        currentValue,
                                        dataType,
                                        isWritable,
                                        DateTime.Now
                                    );
                                }
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                LogManager.LogError($"加载订阅点数据失败：{ex.Message}", ex);
                ShowStatusMessage($"加载订阅点数据失败：{ex.Message}", false);
            }
        }

        /// <summary>
        /// 重写订阅方法，订阅特定的节点
        /// </summary>
        protected override void SubscribeToOpcUaData()
        {
            // 调用基类方法订阅所有数据变化
            base.SubscribeToOpcUaData();

            // 也可以订阅特定节点（如果需要的话）
            // SubscribeToNode("ns=2;s=Motor.Start");
            // SubscribeToNode("ns=2;s=Motor.Speed");
            // SubscribeToNode("ns=2;s=Production.Count");
        }

        /// <summary>
        /// 处理数据变化（在UI线程上）
        /// </summary>
        protected override void OnDataChangedOnUIThread(string nodeId, object value)
        {
            // 记录数据变更
            // Log日志量太大 ，暂时注释掉
            //LogManager.LogInfo($"OPC UA数据变更 - 节点: {nodeId}, 新值: {value}");

            // 通过数据模型来获取和更新数据
            var dataModel = GetDataModel("TwistMachine");
            if (dataModel != null)
            {
                UpdateUIFromModel(dataModel);
                UpdateDataGridView(dataModel);
            }

            // 更新最后更新时间
            lblLastUpdateTime.Text = $"最后更新: {DateTime.Now:yyyy-MM-dd HH:mm:ss}";
        }

        /// <summary>
        /// 更新DataGridView中的数据
        /// </summary>
        private void UpdateDataGridView(DynamicDataModel dataModel)
        {
            try
            {
                foreach (System.Data.DataRow row in subscriptionDataTable.Rows)
                {
                    var propertyName = row["PropertyName"].ToString();
                    var currentValue = dataModel.GetValue(propertyName);
                    if (currentValue != null)
                    {
                        row["CurrentValue"] = currentValue;
                        row["LastUpdate"] = DateTime.Now;
                    }
                }
            }
            catch (Exception ex)
            {
                LogManager.LogError($"更新DataGridView失败: {ex.Message}", ex);
                System.Diagnostics.Debug.WriteLine($"更新DataGridView失败: {ex.Message}");
            }
        }

        /// <summary>
        /// 从数据模型更新UI
        /// </summary>
        private void UpdateUIFromModel(DynamicDataModel dataModel)
        {
            try
            {
                // 更新电机状态
                var motorStart = GetModelValue<bool>(dataModel, "MotorStart");
                lblMotorStatus.Text = $"电机状态: {(motorStart ? "运行" : "停止")}";
                lblMotorStatus.ForeColor = motorStart ? Color.Green : Color.Red;

                // 更新温度（原来的电机转速显示）
                var temperature = GetModelValue<int>(dataModel, "wendu0");
                lblMotorSpeed.Text = $"温度: {temperature} 度";

                // 更新生产计数
                var productCount = GetModelValue<int>(dataModel, "ProductCount");
                lblProductionCount.Text = $"生产计数: {productCount}";

                // 可以根据需要添加更多属性的更新
                // var currentSpeed = GetModelValue<double>(dataModel, "CurrentSpeed");
                // var pressure = GetModelValue<double>(dataModel, "Pressure1");
            }
            catch (Exception ex)
            {
                // 记录错误但不中断UI更新
                LogManager.LogError($"更新UI失败: {ex.Message}", ex);
                System.Diagnostics.Debug.WriteLine($"更新UI失败: {ex.Message}");
            }
        }

        /// <summary>
        /// 从数据模型获取属性值
        /// </summary>
        private T GetModelValue<T>(DynamicDataModel dataModel, string propertyName, T defaultValue = default(T))
        {
            try
            {
                var value = dataModel?.GetValue(propertyName);
                if (value != null && value is T)
                {
                    return (T)value;
                }
                // 尝试类型转换
                if (value != null)
                {
                    return (T)Convert.ChangeType(value, typeof(T));
                }
                return defaultValue;
            }
            catch
            {
                return defaultValue;
            }
        }

        /// <summary>
        /// 处理连接状态变化（在UI线程上）
        /// </summary>
        protected override void OnConnectionStatusChangedOnUIThread(bool isConnected)
        {
            lblConnectionStatus.Text = $"连接状态: {(isConnected ? "已连接" : "未连接")}";
            lblConnectionStatus.ForeColor = isConnected ? Color.Green : Color.Red;

            // 记录连接状态变化
            //LogManager.LogOpcUaConnectionStatus(OpcUaService?. ?? "Unknown", isConnected ? "已连接" : "未连接");

            // 根据连接状态启用/禁用控制按钮
            btnStartMotor.Enabled = isConnected;
            btnStopMotor.Enabled = isConnected;
            btnResetCounters.Enabled = isConnected;
            btnRefreshData.Enabled = isConnected;
        }

        /// <summary>
        /// 启动电机按钮点击事件
        /// </summary>
        private async void BtnStartMotor_Click(object sender, EventArgs e)
        {
            var result = await WriteNodeAsync("ns=2;s=Motor.Start", true);
            ShowOperateResult(result, "电机启动命令已发送");

            // 或者通过数据模型操作
            var dataModel = GetDataModel();
            dataModel?.StartMachine();
        }

        /// <summary>
        /// 停止电机按钮点击事件（改为写温度方式）
        /// </summary>
        private async void BtnStopMotor_Click(object sender, EventArgs e)
        {
            try
            {
                var mapper = GetDynamicMapper();
                if (mapper != null)
                {
                    // 使用DynamicMapper的WritePropertiesByNameAsync方法
                    var properties = new Dictionary<string, object>
                    {
                        { "zhuansu", 251 }
                    };
                    var result = await mapper.WritePropertiesByNameAsync(properties);
                    ShowOperateResult(result, "电机停止命令已发送");
                }
                else
                {
                    var result = await WriteNodeAsync("ns=2;s=通道 1.温控设备.zhuansu", 251);
                    ShowOperateResult(result, "电机停止命令已发送");
                }
            }
            catch (Exception ex)
            {
                LogManager.LogError($"停止电机失败：{ex.Message}", ex);
                ShowStatusMessage($"停止电机失败：{ex.Message}", false);
            }
        }

        /// <summary>
        /// 重置计数器按钮点击事件
        /// </summary>
        private async void BtnResetCounters_Click(object sender, EventArgs e)
        {
            var result = await WriteNodeAsync("ns=2;s=Production.Count", 0);
            ShowOperateResult(result, "计数器重置命令已发送");

            // 或者通过数据模型操作
            var dataModel = GetDataModel();
            dataModel?.ResetCounters();
        }

        /// <summary>
        /// 刷新数据按钮点击事件
        /// </summary>
        private async void BtnRefreshData_Click(object sender, EventArgs e)
        {
            try
            {
                // 开始刷新OPC UA数据
                var result = await OpcUaService.ReadAllDataAsync();
                if (result.IsSuccess)
                {
                    // OPC UA数据刷新成功
                    ShowStatusMessage("数据刷新成功", true);
                }
                else
                {
                    // OPC UA数据刷新失败
                    ShowStatusMessage($"数据刷新失败：{result.Message}", false);
                }
            }
            catch (Exception ex)
            {
                LogManager.LogError($"刷新OPC UA数据时发生异常：{ex.Message}", ex);
                ShowStatusMessage($"刷新数据时发生异常：{ex.Message}", false);
            }
        }

        /// <summary>
        /// DataGridView单元格编辑结束事件
        /// </summary>
        private async void DgvSubscriptions_CellEndEdit(object sender, DataGridViewCellEventArgs e)
        {
            try
            {
                // 只处理"当前值"列的编辑
                if (e.ColumnIndex != dgvSubscriptions.Columns["CurrentValue"].Index)
                    return;

                var row = dgvSubscriptions.Rows[e.RowIndex];
                var propertyName = row.Cells["PropertyName"].Value?.ToString();
                var newValue = row.Cells["CurrentValue"].Value;
                // var isWritable = Convert.ToBoolean(row.Cells["IsWritable"].Value);
                var dataType = row.Cells["DataType"].Value?.ToString();
                var nodeId = row.Cells["NodeId"].Value?.ToString();

                // 验证输入
                if (string.IsNullOrEmpty(propertyName))
                {
                    ShowStatusMessage("属性名称不能为空", false);
                    return;
                }

                //if (!isWritable)
                //{
                //    MessageBox.Show($"属性 '{propertyName}' 不可写", "权限错误", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                //    return;
                //}

                // 验证值的有效性
                if (!ValidateValue(newValue, dataType, out string validationError))
                {
                    ShowStatusMessage($"输入值无效：{validationError}", false);
                    // 恢复原值
                    LoadSubscriptionData();
                    return;
                }

                var mapper = GetDynamicMapper();
                if (mapper != null)
                {
                    // 检查连接状态
                    var serviceManager = twistmachinev2.OPCUA.OpcUaServiceManager.Instance;
                    if (!serviceManager.IsConnected)
                    {
                        ShowStatusMessage("OPC UA连接已断开，请先连接服务器", false);
                        return;
                    }

                    // 使用DynamicMapper的WritePropertiesByNameAsync方法
                    var properties = new Dictionary<string, object>
                    {
                        { propertyName, newValue }
                    };

                    var result = await mapper.WritePropertiesByNameAsync(properties);

                    if (result.IsSuccess)
                    {
                        // 记录成功的数据变更
                        //LogManager.LogOpcUaDataChange(nodeId, "原值", newValue, "用户操作");
                        // OPC UA数据写入成功

                        ShowStatusMessage($"属性 '{propertyName}' 修改成功 (节点ID: {nodeId}, 新值: {newValue})", true);
                        // 更新最后更新时间
                        row.Cells["LastUpdate"].Value = DateTime.Now;
                    }
                    else
                    {
                        string errorMsg = $"属性 '{propertyName}' 修改失败\n";
                        errorMsg += $"节点ID: {nodeId}\n";
                        errorMsg += $"尝试写入值: {newValue}\n";
                        errorMsg += $"数据类型: {dataType}\n";
                        errorMsg += $"错误详情: {result.Message}";

                        // 记录失败的数据变更尝试
                        LogManager.LogError($"OPC UA数据写入失败 - 属性: {propertyName}, 节点ID: {nodeId}, 尝试写入值: {newValue}, 数据类型: {dataType}, 错误: {result.Message}");

                        ShowStatusMessage($"属性 '{propertyName}' 修改失败: {result.Message}", false);

                        // 恢复原值
                        LoadSubscriptionData();
                    }
                }
                else
                {
                    ShowStatusMessage("无法获取DynamicMapper实例，请检查OPC UA服务是否正常初始化", false);
                }
            }
            catch (Exception ex)
            {
                string errorMsg = $"处理值变更时发生异常\n";
                errorMsg += $"异常类型: {ex.GetType().Name}\n";
                errorMsg += $"异常消息: {ex.Message}\n";
                if (ex.InnerException != null)
                {
                    errorMsg += $"内部异常: {ex.InnerException.Message}\n";
                }
                errorMsg += $"堆栈跟踪: {ex.StackTrace}";

                // 记录异常详情
                LogManager.LogError($"处理OPC UA数据变更时发生异常", ex);

                ShowStatusMessage($"处理值变更时发生异常: {ex.Message}", false);

                // 恢复原值
                LoadSubscriptionData();
            }
        }

        /// <summary>
        /// DataGridView按键事件（处理回车键）
        /// </summary>
        private void DgvSubscriptions_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                e.Handled = true; // 阻止默认的回车行为

                var currentCell = dgvSubscriptions.CurrentCell;
                if (currentCell != null && currentCell.ColumnIndex == dgvSubscriptions.Columns["CurrentValue"].Index)
                {
                    // 结束编辑状态，触发CellEndEdit事件
                    dgvSubscriptions.EndEdit();
                }
            }
            else if (e.KeyCode == Keys.Escape)
            {
                // ESC键取消编辑
                e.Handled = true;
                dgvSubscriptions.CancelEdit();
                LoadSubscriptionData(); // 恢复原值
            }
        }

        /// <summary>
        /// 显示状态消息
        /// </summary>
        /// <param name="message">消息内容</param>
        /// <param name="isSuccess">是否为成功消息</param>
        private void ShowStatusMessage(string message, bool isSuccess)
        {
            if (statusStrip1 != null && statusStrip1.Items.Count > 0)
            {
                var statusLabel = statusStrip1.Items[0] as ToolStripStatusLabel;
                if (statusLabel != null)
                {
                    statusLabel.Text = message;
                    statusLabel.ForeColor = isSuccess ? Color.Green : Color.Red;

                    // 3秒后恢复默认状态
                    var timer = new System.Windows.Forms.Timer();
                    timer.Interval = 3000;
                    timer.Tick += (s, e) =>
                    {
                        statusLabel.Text = "就绪";
                        statusLabel.ForeColor = SystemColors.ControlText;
                        timer.Stop();
                        timer.Dispose();
                    };
                    timer.Start();
                }
            }
        }

        /// <summary>
        /// 验证输入值的有效性
        /// </summary>
        /// <param name="value">输入值</param>
        /// <param name="dataType">数据类型</param>
        /// <param name="errorMessage">错误消息</param>
        /// <returns>是否有效</returns>
        private bool ValidateValue(object value, string dataType, out string errorMessage)
        {
            errorMessage = string.Empty;

            if (value == null)
            {
                errorMessage = "值不能为空";
                return false;
            }

            string valueStr = value.ToString().Trim();
            if (string.IsNullOrEmpty(valueStr))
            {
                errorMessage = "值不能为空字符串";
                return false;
            }

            try
            {
                switch (dataType?.ToLower())
                {
                    case "bool":
                    case "boolean":
                        if (!bool.TryParse(valueStr, out _))
                        {
                            errorMessage = "请输入有效的布尔值（true/false）";
                            return false;
                        }
                        break;
                    case "byte":
                        if (!byte.TryParse(valueStr, out _))
                        {
                            errorMessage = "请输入有效的字节值（0-255）";
                            return false;
                        }
                        break;
                    case "short":
                    case "int16":
                        if (!short.TryParse(valueStr, out _))
                        {
                            errorMessage = "请输入有效的16位整数值";
                            return false;
                        }
                        break;
                    case "int":
                    case "int32":
                        if (!int.TryParse(valueStr, out _))
                        {
                            errorMessage = "请输入有效的32位整数值";
                            return false;
                        }
                        break;
                    case "long":
                    case "int64":
                        if (!long.TryParse(valueStr, out _))
                        {
                            errorMessage = "请输入有效的64位整数值";
                            return false;
                        }
                        break;
                    case "float":
                    case "single":
                        if (!float.TryParse(valueStr, out _))
                        {
                            errorMessage = "请输入有效的单精度浮点数值";
                            return false;
                        }
                        break;
                    case "double":
                        if (!double.TryParse(valueStr, out _))
                        {
                            errorMessage = "请输入有效的双精度浮点数值";
                            return false;
                        }
                        break;
                    case "decimal":
                        if (!decimal.TryParse(valueStr, out _))
                        {
                            errorMessage = "请输入有效的十进制数值";
                            return false;
                        }
                        break;
                    case "datetime":
                        if (!DateTime.TryParse(valueStr, out _))
                        {
                            errorMessage = "请输入有效的日期时间格式";
                            return false;
                        }
                        break;
                    case "string":
                        // 字符串类型通常不需要特殊验证
                        break;
                    default:
                        // 未知类型，允许通过
                        break;
                }
                return true;
            }
            catch (Exception ex)
            {
                errorMessage = $"值验证时发生错误: {ex.Message}";
                return false;
            }
        }

        /// <summary>
        /// 窗体加载事件
        /// </summary>
        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);

            // 初始化显示连接状态
            OnConnectionStatusChangedOnUIThread(OpcUaService.IsConnected);

            // 加载订阅点数据
            LoadSubscriptionData();
        }

        /// <summary>
        /// 显示操作结果消息（覆盖基类方法，使用状态栏显示）
        /// </summary>
        /// <param name="result">操作结果</param>
        /// <param name="successMessage">成功时显示的消息</param>
        protected new void ShowOperateResult(OperateResult result, string successMessage = "操作成功")
        {
            if (result.IsSuccess)
            {
                ShowStatusMessage(successMessage, true);
            }
            else
            {
                ShowStatusMessage($"操作失败：{result.Message}", false);
            }
        }

        /// <summary>
        /// 显示操作结果消息（泛型版本，覆盖基类方法，使用状态栏显示）
        /// </summary>
        /// <typeparam name="T">结果类型</typeparam>
        /// <param name="result">操作结果</param>
        /// <param name="successMessage">成功时显示的消息</param>
        protected new void ShowOperateResult<T>(OperateResult<T> result, string successMessage = "操作成功")
        {
            if (result.IsSuccess)
            {
                ShowStatusMessage(successMessage, true);
            }
            else
            {
                ShowStatusMessage($"操作失败：{result.Message}", false);
            }
        }
    }
}